package com.ray.ba.starter.code.generator.util;

import lombok.experimental.UtilityClass;

/**
 * StringUtil
 *  -  https://blog.csdn.net/li740207611/article/details/87367383
 *  - https://github.com/slacrey/heron-project/blob/master/heron-common/src/main/java/com/loadburn/heron/utils/StringUtils.java
 * @author ray
 * @date 2020/4/29
 */
@UtilityClass
public class StringUtil {

    /**
     * 驼峰转下划线
     *   例如：HelloWorld->HELLO_WORLD， helloWorld->HELLO_WORLD，
     * @param str
     * @return
     */
    public String toUnderscoreCase(String str){
        if(str == null || str.isEmpty() ){
            return str;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c) && i != 0) {
                sb.append("_");
            }
            sb.append(Character.toUpperCase(c));
        }
        return sb.toString();
    }


    /**
     * 下划线转驼峰
     *  例如：HELLO_WORLD->HelloWorld
     * @param str
     * @return
     */
    public String toUpperCamelCase(String str){
        if(str == null || str.isEmpty() ){
            return str;
        }

        boolean needUpperCase = true;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if(c == '_'){
                needUpperCase = true;
                continue;
            }

            if(needUpperCase){
                needUpperCase =false;
                sb.append(Character.toUpperCase(c));
            }else{
                sb.append(Character.toLowerCase(c));
            }
        }
        return sb.toString();
    }

    /**
     * 下划线转驼峰
     *  例如：HELLO_WORLD->HelloWorld
     * @param str
     * @return
     */
    public String toLowerCamelCase(String str){
        if(str == null || str.isEmpty() ){
            return str;
        }

        boolean needUpperCase = false;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if(c == '_'){
                needUpperCase = true;
                continue;
            }

            if(needUpperCase){
                needUpperCase =false;
                sb.append(Character.toUpperCase(c));
            }else{
                sb.append(Character.toLowerCase(c));
            }
        }
        return sb.toString();
    }



}
